package com.chen.controller.qq;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.chen.common.Result;
import com.chen.pojo.User;
import com.chen.pojo.UserRole;
import com.chen.service.Impl.UserServiceImpl;
import com.chen.utils.QQHttpClient;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.net.URLEncoder;
import java.util.Date;
import java.util.UUID;


/**
 * QQ第三方登陆接口
 */
@Controller
@Log4j2
@Api(value = "QQLoginController", tags = "QQ登录")
public class QQLoginController {
    @Value("${qq.oauth.http}")
    private String http;

    @Autowired
    private UserServiceImpl userService;

    /**
     * 发起请求
     *
     * @param session
     * @return
     */
    @GetMapping("/qq/oauth")
    @ResponseBody
    @ApiOperation("QQ登录回调")
    public Result qq(HttpSession session) {
        //QQ互联中的回调地址
        String backUrl = "http://545jv5.natappfree.cc/qq/user";

        //用于第三方应用防止CSRF攻击
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        session.setAttribute("state", uuid);

        //Step1：获取Authorization Code
        String url = "https://graph.qq.com/oauth2.0/authorize?response_type=code" +
                "&client_id=" + QQHttpClient.APPID +
                "&redirect_uri=" + URLEncoder.encode(http) +
                "&state=" + uuid;
        return Result.success(url);
    }

    /**
     * QQ回调 注意 @GetMapping("/qq/callback")路径
     * 是要与QQ互联填写的回调路径一致(我这里因为前端请求愿意不用写成  api/qq/callback)
     *
     * @param request
     * @return
     */
    @GetMapping("/qq/user")
    @ResponseBody
    public void qqcallback(HttpServletRequest request, HttpServletResponse response) throws Exception {
        response.setContentType("text/html; charset=utf-8");  // 响应编码
        HttpSession session = request.getSession();
        //qq返回的信息：http://graph.qq.com/demo/index.jsp?code=9A5F************************06AF&state=test
        String code = request.getParameter("code");
        String state = request.getParameter("state");
        String uuid = (String) session.getAttribute("state");

        if (uuid != null) {
            if (!uuid.equals(state)) {
                throw new Exception("QQ,state错误");
            }
        }
        //Step2：通过Authorization Code获取Access Token
        String backUrl = "http://545jv5.natappfree.cc/qq/user";
        String url = "https://graph.qq.com/oauth2.0/token?grant_type=authorization_code" +
                "&client_id=" + QQHttpClient.APPID +
                "&client_secret=" + QQHttpClient.APPKEY +
                "&code=" + code +
                "&redirect_uri=" + http;

        String access_token = QQHttpClient.getAccessToken(url);

        //Step3: 获取回调后的 openid 值
        url = "https://graph.qq.com/oauth2.0/me?access_token=" + access_token;
        String openid = QQHttpClient.getOpenID(url);

        //Step4：获取QQ用户信息
        url = "https://graph.qq.com/user/get_user_info?access_token=" + access_token +
                "&oauth_consumer_key=" + QQHttpClient.APPID +
                "&openid=" + openid;

        JSONObject jsonObject = QQHttpClient.getUserInfo(url);

        //可以放到Redis和mysql中
        //session.setAttribute("openid",openid);  //openid,用来唯一标识qq用户
        //session.setAttribute("nickname",(String)jsonObject.get("nickname")); //QQ名
        //session.setAttribute("figureurl_qq_2",(String)jsonObject.get("figureurl_qq_2")); //大小为100*100像素的QQ头像URL
        User us = userService.getOpenid(openid);
        if (us == null) {//用户不存在
            User u = new User();
            u.setUsername(openid);
            u.setPassword("123456");
            u.setQqOpenId(openid);
            u.setRegtime(DateUtil.formatTime(new Date()));
            u.setRole(0);
            u.setStatus(1);
            u.setAge(18);
            Date date = new Date();

            String format = DateUtil.format(date, "yyyy-MM-dd HH:mm:ss");
            u.setAvatar(jsonObject.getString("figureurl_qq"));
            u.setNick(jsonObject.getString("nickname"));

            //注册
            userService.save(u);
            //redirect:../admin/dashboard
            // return "<script>window.close();</script>";
            us = u;
        }
//        User us=userService.getOpenid(openid);
        else {
            //return "<script>window.opener.localStorage.setItem('username', '"+JSON.toJSONString(us)+"');window.close();</script>";
        }
//        us.setPassword("123456");
//        Result<UserInfo> userInfoResult = userService.login(us.getId());
//        UserInfo userInfo = userInfoResult.getData();
        response.sendRedirect("http://localhost:9527/#/authRedirect?userid=" + us.getId());

        // response.setHeader("userInfo",JSONObject.toJSONString(userInfo));
    }

    @GetMapping("/auth/login/{userId}")
    @ResponseBody
    public Result authLogin(@PathVariable("userId") Integer userId) {
        return userService.login(userId);
    }

}
